﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection.Metadata;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Simple.Common.Helpers
{
    public static class RequestHelper
    {
        private static Dictionary<string, string> ipAddress = new Dictionary<string, string>();
        /// <summary>
        /// 通过IP得到IP所在地省市（Porschev）
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string GetAddressByIp(string ip)
        {
            var address = string.Empty;
            try
            {
                if (ipAddress.ContainsKey(ip))
                {
                    return ipAddress[ip];
                }
                if (!IsPrivateNetwork(ip))
                {
                    string url = "https://www.cz88.net/api/cz88/ip/geo?ip=" + ip;
                    string html = GetHtml(url);
                    if (html != null)
                    {
                        JObject jsonObj = JObject.Parse(html);
                        var dataJson = jsonObj["data"];
                        if (dataJson != null)
                        {
                            //var country = dataObj.Value<string>("country");
                            var province = dataJson.Value<string>("province");
                            var city = dataJson.Value<string>("city");
                            var districts = dataJson.Value<string>("districts");
                            address = province + "-" + city + "-" + districts;
                        }
                    }
                }

                ipAddress.Add(ip, address);
            }
            catch
            {

            }
            return address;
        }
        public static bool IsPrivateNetwork(string ipv4Address)
        {
            if (IPAddress.TryParse(ipv4Address, out var ip))
            {
                byte[] ipBytes = ip.GetAddressBytes();
                if (ipBytes[0] == 127) return true;
                if (ipBytes[0] == 10) return true;
                if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) return true;
                if (ipBytes[0] == 192 && ipBytes[1] == 168) return true;
            }
            return false;
        }

        /// <summary>
        /// 获取HTML源码信息(Porschev)
        /// </summary>
        /// <param name="url">获取地址</param>
        /// <returns>HTML源码</returns>
        public static string GetHtml(string url)
        {
            string str = string.Empty;
            try
            {
                Uri uri = new Uri(url);
                WebRequest wr = WebRequest.Create(uri);
                Stream s = wr.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                str = sr.ReadToEnd();
            }
            catch (Exception e)
            {
            }
            return str;
        }

        public static string DevicePost(string url, string text,string token="")
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";

            byte[] data = Encoding.UTF8.GetBytes(text);

            req.ContentLength = data.Length; 
            if(!string.IsNullOrEmpty(token))
                req.Headers.Set("Access_token", token);
            try
            {

                using (Stream reqStream = req.GetRequestStream()) 
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close(); 
                }

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
                Stream stream = resp.GetResponseStream();
                
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {

            }
            return result;
        }

    }
}
